<?php
/**
 *      订单管理控制器
 */

namespace Home\Controller;
use Think\Controller;

class OrderController extends CommonController{

    public function _initialize() {
        parent::_initialize();
        $this->dbname = 'cash_'.CONTROLLER_NAME;
    }
    public function _collfilter($map,$page){

        //$map['cash_order.status'] = ['EQ','4']; 
        //$map['cash_order.collection_id'] = session('uid');
       
        if(isset($_REQUEST['collection_time']) && $_REQUEST['collection_time'] != ''){
             switch ($_REQUEST['collection_time']) {
               case '1':
                 $map['collection_time']   = ['GT','0'];break;
               case '-1':
                 $map['collection_time']   = ['EQ','0'];break;
               case '2':
			     $map['dk.collection_id']  = session('uid');
                 //$map['cash_order.status'] = ['EQ','5'];
                 $map['dk.trans_type']     = ['neq','3'];
                 $map['dk.status']         = ['EQ','S'];break;
               case '3':
			     $map['dk.collection_id']  = session('uid');
                 $map['dk.trans_type']     = ['EQ','3'];
                 $map['dk.status']         = ['EQ','S']; break;
             }
        }else{
			$map['cash_order.status'] = ['EQ','4']; 
            $map['cash_order.collection_id'] = session('uid');
		}
        if((isset($_REQUEST['time1']) && $_REQUEST['time1'] != '') && (isset($_REQUEST['time2']) && $_REQUEST['time2'] != '')){
            $wheretime = ['BETWEEN',[strtotime($_REQUEST['time1']),strtotime($_REQUEST['time2'])]];
            if(in_array($_REQUEST['collection_time'],['2','3'])){
                 $map['dk.k_time']    = $wheretime;
            }else{
                 $map['expire_time']  = $wheretime;
            }
        }else{
            $t     = time();    
            $time  = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t)); 
            if(in_array($_REQUEST['collection_time'],['2','3'])){
                 $times = M('user')->where("id = {$map['dk.collection_id']}")->field('creat_time')->find();
                 $map['dk.k_time']    = ['BETWEEN',[$times['creat_time'],time()]];
                 //$map['dk.k_time']    = ['LT',time()];
            }else{
                 $map['expire_time']  = ['LT',$time];
            }       
        }
        if(isset($_REQUEST['keys']) && $_REQUEST['keys'] != ''){
            $map['info.user_name|mob.mobile_phone']   = ['like','%'.urldecode(trim($_REQUEST['keys'])).'%'];     
        }
		if(isset($_REQUEST['page']) && !empty($_REQUEST['page'])){
			$page = $_REQUEST['page'];
		}
        $_REQUEST ['orderField'] = 'expire_time';
		$arr['map'] = $map;
		$arr['page'] = $page;
        return $arr;
    }

    function _filter(&$map) {
        if(!in_array(session('uid'),C('ADMINISTRATOR'))){
            $map[]=array("uid"=>array('EQ', session("uid")));
        }
    }
    
    public function _befor_index(){
        
        $re = $_GET['re'];
        $model = D($this->dbname);
        $map = array();
        $login_id = session('uid');
      
        if($re == 'nopass'){
            $result = $model
                        ->join('cash_user_credit ON cash_order.uid = cash_user_credit.uid');
        }else if($re == 'pass'){
            $result = $model
                        ->join('cash_user_credit ON cash_order.uid = cash_user_credit.uid');
        }else if($re == 'daishen'){
            $result = $model
                        ->join('cash_user_credit ON cash_order.uid = cash_user_credit.uid');
        }else{
            $result = $model
                        ->join('cash_user_credit ON cash_order.uid = cash_user_credit.uid');
        }
        $orderall = $this->orderAll($map,$re,$login_id);
        if(isset($_REQUEST['keys']) && $_REQUEST['keys'] != ''){
            if(!is_numeric($_REQUEST['keys'])){
               // $uid = $this->uname($_REQUEST['keys']);
               // $map['cash_order.uid'] = $uid['id'];
                $result = $result->join('cash_user_info ON cash_order.uid = cash_user_info.id');
                $orderall['cash_user_info.user_name'] = array('like','%'.urldecode(trim($_REQUEST['keys'])).'%');
            }else{
                $orderall['cash_order.uid'] = $_REQUEST['keys']; 
            }    
        }
        $field = "cash_order.*,cash_user_credit.mobile_phone,cash_user_credit.user_info,cash_user_credit.identity,cash_user_credit.bankcard";
        $this->_list($result,$orderall,false,$field,1,false);
        $this->assign('suffit',$_GET['re']);
        // $this->display();
        return; 
    }


    //收页订单展示删选条件
    public function orderAll($map,$re,$login_id){
        if($re == 'nopass'){
            $map['cash_order.vstatus'] = -1;
            $map['cash_order.login_id'] = $login_id;
            $map['cash_order.status'] = 1;
        }elseif($re == 'pass'){
            $map['cash_order.vstatus'] = 1;
            $map['cash_order.login_id'] =$login_id;
            $map['cash_order.status'] = 1; 
        }elseif($re == 'daishen'){
            $map['cash_order.vstatus'] = 0;
            $map['cash_order.login_id'] = $login_id;
            $map['cash_order.status'] = 1;
        }else{
            $admin = C('ADMINISTRATOR');
            if(!in_array($login_id,$admin)){
                $map['cash_order.login_id'] = $login_id;
                $map['cash_order.status'] = 1;
                $map['cash_order.vstatus'] = 0;
            }
            
            $map['cash_order.creat_time'] = ['neq','0'];
            //var_dump($map);exit;
        }
       
        return $map;
    }

    //计算当前登录人审核单子的数量  配合index使用
    public function basenum(){
        $model = D($this->dbname);
        $login_id = session('uid');
        $result = $model->join('cash_user_credit ON cash_order.uid = cash_user_credit.uid')->where("status = 1 AND vstatus = 1 AND login_id = {$login_id}")->count();
        return $result;
    }

    public function _after_list($list,$status){
        
        if($status == 2){
            //var_dump($status);exit;
            $model = D($this->dbname);
            for($i=0;$i<count($list);$i++){
                //拒绝
                $list[$i][] = $model->where("uid = {$list[$i]['id']} AND status = -2")->count();
                //成功  已还款
                $list[$i][] = $model->where("uid = {$list[$i]['id']} AND status = 5")->count();
                //取消
                $list[$i][] = $model->where("uid = {$list[$i]['id']} AND status = -1")->count();
             }
        }elseif($status == 1){
            $list = $this->bankcard($this->identity($this->info($this->phone($list))));
            foreach ($list as $k=>$v) {
                $list[$k]['user_name'] = M('cash_user_info')->where("id=".$v['uid'])->getField('user_name');          
            }
        }else{
            $list = $this->bankcard($this->identity($this->info($this->phone($list))));
        }
        
        return $list;
    }
    
    public function daishen() {
        $model = D($this->dbname);
        $login_id = session('uid');
        $result = $model->where("vstatus = 0 AND login_id = {$login_id}")->select();
        $this->assign('list',$result);
        $this->display();
    }
    
    public function _befor_add(){

    }
    
    public function _befor_insert($data){
    
    }
    
    public function _after_add($id){
    
    }
    
    public function _befor_edit(){
        $model = D($this->dbname);
        $uid = $model->field('uid')->where("order_id = {$_REQUEST['id']}")->find();
    		$file = json_decode($this->api($uid['uid'])); 
    		$qizha = $this->qizha($uid['uid']);
    		$guanzhu = $this->guanzhu($uid['uid']);
            $readtxt = $this->read_txt($uid['uid']);
		    $edite_linkman = $this->edite_linkman($_REQUEST['id']);

    		if($qizha['status'] == 1){
    			$this->assign('qizha',$qizha['status']);
    			$this->assign('qizhaMsg',$qizha['data']);
    		}
    		
    		if($guanzhu['status'] == 1){
    			$this->assign('guanzhu',$guanzhu['status']);
    			$this->assign('guanzhuM',$guanzhu['data']);
    		}
    		
    		if($file->status == 1){
    			$val = json_decode($file->data,true);
    			$this->assign('status',$file->status);
    			$this->assign('msg',$val);
    		}

            if($readtxt['status'] == 1){
                $this->assign('readtxt',$readtxt['status']);
                $this->assign('readtxtM',json_decode($readtxt['data']));
            }
            
            //借款详情
            $borrowMoney = $this->borrowMoney($_REQUEST['id']);
			//欺诈分数
			$score = $this->qizhaNum($uid['uid']);
    		$yM = M('cash_user_mobile')->field('mobile_phone')->where("uid = {$uid['uid']}")->find();
    		$bankM = M('cash_user_bank')->field('yu_tel,bank_name,bank_num')->where("uid = {$uid['uid']}")->find();
            $bank = M('cash_bank_list')->field('b_name')->where("b_id = {$bankM['bank_name']}")->find();
            //获取已发送的短信
            //$duanxin = M('cash_duanxin')->where("uid = {$uid['uid']}")->field('phone')->find();
            $duanxin = $this->overDX($uid['uid']);
            //var_dump($duanxin);exit;
            $this->assign('duanxin',$duanxin);
            $this->assign('bank',$bank);
    		$this->assign('yuTel',$bankM);
    		$this->assign('mobilePhone',$yM);
            $this->assign('borrowMoney',$borrowMoney);
            $this->assign('order_id',$_REQUEST['id']);
            $this->assign('linkman',$edite_linkman);
			$this->assign('score',$score['score']);
            //拒绝理由
            $reson = M('cash_order_reason')->join("xy_user ON cash_order_reason.login_id = xy_user.id","LEFT")->where("cash_order_reason.uid = {$uid['uid']}")->field('cash_order_reason.reason,cash_order_reason.data,xy_user.truename')->order('data desc')->find();
            $result = $model
                        ->join("cash_user_credit ON {$uid['uid']} = cash_user_credit.uid")
                        ->join('cash_user_info as a ON cash_order.uid = a.id')
                        ->join('cash_user_img ON cash_order.uid = cash_user_img.uid')
                        ->join('left join cash_user_wx ON cash_order.uid = cash_user_wx.wx_uid')
                        ->where("order_id = {$_REQUEST['id']}")->field('cash_user_credit.*,cash_user_img.*,cash_user_wx.*,a.*,cash_order.*,a.income as userincome,a.creat_time as zhuce')->find();
            //var_dump($result);exit;
            //获取当前用户的等级
            $grade = M('cash_user_grade')->where("id = {$result['we_grade']}")->field('grade')->find();
            $jiekuan = $model->where("order_id = {$_REQUEST['id']}")->field('creat_time')->find();
            $this->assign('grade',$grade['grade']);
            $this->assign('cre_time',$jiekuan['creat_time']);
            $this->assign('reason',$reson);
            $this->assign('wenum',$result['we_num']);
            $result = $this->sta($this->sex($result));
            $this->assign('re',$result);
           // $this->display();
           // exit;
    }

    //获取已发送的短信
    public function overDX($uid){
        $result = M('cash_duanxin')->where("uid = {$uid}")->find();

        //判断当前用户是否已经发送过短信
        if($result == null){  //没有发送过短信
            //给该用户发送短信
            $arr['status'] = 1;
            $arr['phone'] = '';
        }else{
            //将phone字符串转化为数组
            $arr['phone'] = explode(',',$result['phone']);
           
            //获取创建的时间  转化未ymd
            $ymd = date('Y-m-d',$result['create_time']);

            //判断当前时间是否大于$ymd
            if(date('Y-m-d',time()) > $ymd){
                echo '可以发送短信';
                //判断当前发送的短信数是否超出5条
                    $arr['status'] = 1;
            }else{
                echo '不可以发送短信';
                if(count($arr['phone']) >= 6){
                    $arr['status'] = 0;
                }else{
                    $arr['status'] = 1;
                }
            }  
        }
        //$value = '17710470581';
        //将phone字符串转化为数组
        //$phone = explode(',',$result['phone']);
        //判断$value值是否是在数组中
        //$aa = in_array($value,$phone);
        return $arr;
    }
	
	//获取欺诈分数
	public function qizhaNum($uid){
		$score = M('cash_user_score')->field('score')->where("uid = {$uid}")->find();
		return $score;
	}

    //详情中展示联系人的备注
    public function edite_linkman($order_id){
        $model = M('cash_linkman');
        $result = $model->where("order_id = {$order_id}")->select();
        return $result;
    }

    //借款详情
    public function borrowMoney($order_id){
    
        //获取相关用户的id
        $uid = D($this->dbname)->field('uid')->where("order_id = {$order_id}")->find();

        $val = M('cash_user_info')->join('cash_order ON cash_order.uid = cash_user_info.id')->where("cash_order.status = 5 AND cash_order.uid = {$uid['uid']}")->field('cash_order.loan_time,cash_order.order_id')->select();

        for($i=0;$i<count($val);$i++){
           $val[$i][] = M('cash_bf_dk')->field('k_time,trans_type,trans_type')->where("order_id = {$val[$i]['order_id']} AND trans_type != 3 AND status = 'S'")->select();
           $val[$i][] = M('cash_bf_dk')->where("order_id = {$val[$i]['order_id']} AND trans_type = 3 AND status = 'S'")->count();
        }

       return $val;
    }
    
    public function _befor_update($data){
    
    }
    
    public function _after_edit($id){
     
    }
    
    public function _befor_view($id){
       
    }
    
    public function _befor_del($id){
    
    }

    public function _befor_lock($id){
        $model = D($this->dbname);
        $data = $model->find($id);
            $data['order_id'] = $id;
              if($_GET['va'] == 'pass'){
                  $data['vstatus'] = 1;
                  $msg = '通过';
                  $model->save($data);
              }else if($_GET['va'] == 'passone'){
                  $uid = $_GET['id'];
                  $arr['mobile_phone'] = 2;
                  $arr['user_info'] = 2;
                  $arr['identity'] = 2;
                  $arr['bankcard'] = 2;
                  M('cash_user_credit')->where("uid = {$uid}")->save($arr);
              }else{
                   $data['vstatus'] = -1;
                   $msg = '不通过';
                   $model->save($data);
              }
              $suffit = '/re/'.$_GET['suffit'];
              $this->mtReturn(200,$msg.$id,$_REQUEST['navTabId'],false,$suffit);
    }

    //修改操作
    public function up(){
        if(IS_POST){
            $result = M('cash_user_credit');
            $uid = $_POST['uid'];
            $suffit = '/re/'.$_POST['suffit'];
            $this->code($uid,$_POST['credit'],$_REQUEST,$suffit);
            if($_POST['result'] == 'mobile_phone'){
                $result->mobile_phone = $_POST['credit'];
                $result->phone = 3;
                $result->where("uid = {$uid}")->save();
            }

            if($_POST['result'] == 'user_info'){
                $val = $this->user_info($uid);
                if(!$val){
                    $this->mtReturn(200,"芝麻参数修改失败".$_POST['uid'].'/'.$_POST['result'].'/'.$_POST['credit'],$_REQUEST['navTabId'],true,$suffit); 
                }
                $result->user_info = $_POST['credit'];
                $result->where("uid = {$uid}")->save();
            }

            if($_POST['result'] == 'identity'){
                $result->identity = $_POST['credit'];
                $result->where("uid = {$uid}")->save();
            }
            if($_POST['result'] == 'bankcard'){
                $result->bankcard = $_POST['credit'];
                $result->where("uid = {$uid}")->save();
            }
            $this->mtReturn(200,"添加成功".$_POST['uid'].'/'.$_POST['result'].'/'.$_POST['credit'],$_REQUEST['navTabId'],true,$suffit); 
        }else{
            $this->assign('suffit',$_GET['suffit']);
            $this->assign('va',$_GET['va']);
            $this->assign('uid',$_GET['id']);
            $this->display();
        }
    }

    //修改个人信息状态后执行
    public function user_info($uid){
        $model = M('cash_user_info');
        $model->zm_openid = 0;
        $model->zm_num = 0;
         return $model->where("id = {$uid}")->save();
    }


    //领取任务操作
    public function lq($today_zero){
        if($today_zero < 1508457600){
            $this->mtReturn(202,"暂时没有订单",$_REQUEST['navTabId'],false);
        }
        $model = D($this->dbname);
        $suid = session('uid');
        //$today_zero=strtotime('today');
        //var_dump(date('Y-m-d H:i:s',$today_zero));exit;
        $data = $today_zero-172800;    //172800 
        $count = $model->where("mauto = 2 AND login_id = {$suid} AND status = 1 AND vstatus != 0 AND creat_time > {$data}")->count();
        $num = $model->where("mauto = 2 AND login_id = {$suid} AND status = 1 AND vstatus = 0 AND creat_time > {$data}")->count();
        $zong = $count + $num;
        if($num >= 10){
          $this->mtReturn(202,"当前您的订单过多,请处理完了再来领取",$_REQUEST['navTabId'],false);
        }
        
        $result = $model->where("mauto = 2 AND login_id = 0 AND status = 1 AND creat_time > {$data}")->order('c_time desc')->limit(5)->select();

        if($result == NULL){
            //$this->mtReturn(202,'暂无数据',$_REQUEST['navTabId'],false);
            $datatime = $data-259200;
            $this->lq($datatime);
        }

        for($i=0;$i<count($result);$i++){
            $model->login_id = session('uid');
            $arr = $model->where("order_id = {$result[$i]['order_id']}")->save();
        }

        //随机获取5个  
       //  if(count($result) < 5){
       //      for($i=0;$i<count($result);$i++){
       //        $model->login_id = session('uid');
       //        $arr = $model->where("order_id = {$result[$i]['order_id']}")->save();
       //      }
       //  }else{
       //  $val = array_rand($result,5);
       
       //  for($i=0;$i<count($val);$i++){
       //      $model->login_id = session('uid');
       //      $arr = $model->where("order_id = {$result[$val[$i]]['order_id']}")->save();
       //  }
       // }
       
        $this->mtReturn(200,"领取成功",$_REQUEST['navTabId'],false);
    }


    //拒绝操作
    public function lockss(){
        if(IS_POST){
            //获取允许借款的天数
            $day = $_REQUEST['credit'];
          
            $modelreson = M('cash_order_reason');
            $modelreson->uid = $_POST['uid'];
            $modelreson->order_id = $_POST['order_id'];
            $modelreson->login_id = $_POST['login_id'];
            $modelreson->reason = $_POST['reason'];
            $modelreson->data = date('Y-m-d H:i:s',time());
            $modelreson->login_id = session('uid');
            $result = $modelreson->add();
            $model = D($this->dbname);
            $data = $model->find($_POST['order_id']);
            $data['vstatus'] = -1;
            if($_REQUEST['credit'] == 7){
                $data['collection_mes'] = strtotime(date('Y-m-d')) + 86400*7;
            }else{
                $data['collection_mes'] = strtotime(date('Y-m-d')) + 86400*30;
            };
            $model->save($data);
            $suffit = '/re/'.$_REQUEST['suffit'];
            if($result){
                $this->noPass($_POST['order_id']);
                $this->mtReturn(200,"添加成功".$id,$_REQUEST['navTabId'],true,$suffit);  
            }else{
                $this->mtReturn(202,"添加失败".$id,$_REQUEST['navTabId'],true,$suffit);
            }
        }else{
            $this->assign('suffit',$_GET['suffit']);
            $this->assign('order_id',$_GET['id']);
            $this->assign('uid',$_GET['uid']);
            $this->assign('login_id',session('uid'));
            $this->display();
        }
    }


    //手机号验证
    public function phone($result){
		for($i=0;$i<count($result);$i++){
			if($result[$i]['mobile_phone'] == 0){
				$result[$i]['mobile_phone'] = '未验证';
			}
			if($result[$i]['mobile_phone'] == 1){
				$result[$i]['mobile_phone'] = '已验证';
			}
			if($result[$i]['mobile_phone'] == 2){
				$result[$i]['mobile_phone'] = '已审核';
			}
			if($result[$i]['mobile_phone'] == 3){
				$result[$i]['mobile_phone'] = '未通过';
			}
		}
		return $result;
    }

    //个人信息验证
     public function info($result){
		for($i=0;$i<count($result);$i++){
			if($result[$i]['user_info'] == 0){
				$result[$i]['user_info'] = '未验证';
			}
			if($result[$i]['user_info'] == 1){
				$result[$i]['user_info'] = '已验证';
			}
			if($result[$i]['user_info'] == 2){
				$result[$i]['user_info'] = '已审核';
			}
			if($result[$i]['user_info'] == 3){
				$result[$i]['user_info'] = '未通过';
			}
		}
        return $result;
    }

    //身份验证
    public function identity($result){
		for($i=0;$i<count($result);$i++){
			if($result[$i]['identity'] == 0){
				$result[$i]['identity'] = '未验证';
			}
			if($result[$i]['identity'] == 1){
				$result[$i]['identity'] = '已验证';
			}
			if($result[$i]['identity'] == 2){
				$result[$i]['identity'] = '已审核';
			}
			if($result[$i]['identity'] == 3){
				$result[$i]['identity'] = '未通过';
			}
		}
        return $result;
    }

    //银行卡验证
    public function bankcard($result){
        for($i=0;$i<count($result);$i++){
			if($result[$i]['bankcard'] == 0){
				$result[$i]['bankcard'] = '未验证';
			}
			if($result[$i]['bankcard'] == 1){
				$result[$i]['bankcard'] = '已验证';
			}
			if($result[$i]['bankcard'] == 2){
				$result[$i]['bankcard'] = '已审核';
			}
			if($result[$i]['bankcard'] == 3){
				$result[$i]['bankcard'] = '未通过';
			}
			$result[$i]['creat_time'] = date('Y-m-d H:i:s',$result[$i]['creat_time']);
		}
        return $result;
    }

    //判断性别
    public function sex($result){
        if($result['sex'] == 0){
            $result['sex'] = '未知';
        }

        if($result['sex'] == 1){
            $result['sex'] = '男';
        }

        if($result['sex'] == 2){
            $result['sex'] = '女';
        }
        return $result;
    }
	
	//账号状态
	public function sta($result){
		if($result['status'] == 1){
			$result['status'] = '启用';
		}
		if($result['status'] == 0){
			$result['status'] = '禁用';
		}
		return $result;
	}
	
	//获取接口操作
	public function api($uid){
		$file = file_get_contents("http://hd.hxsmtrz.com/index.php/home/Internal/lmOption/uid/{$uid}") ;
        return $file;
	}
	
	//欺诈信息
	public function qizha($uid){
		$file = file_get_contents("http://hd.hxsmtrz.com/index.php/home/Internal/reCheat/uid/{$uid}");
	    return json_decode($file,true);
	}
	
	//欺诈关注信息
	public function guanzhu($uid){
		$file = file_get_contents("http://hd.hxsmtrz.com/index.php/home/Internal/cheatList/uid/{$uid}");
		return json_decode($file,true);
	}

    //获取联系人的姓名
    public function read_txt($uid){
        $file = file_get_contents("http://hd.hxsmtrz.com/index.php/home/Internal/readtxt/uid/{$uid}");
        return json_decode($file,true);
    }

  //催收订单领取
  public function receive(){
      $uid   = session('uid');
      $model = D($this->dbname);
      $wherecal['collection_id'] = $uid; //collection_id|login_id
      $wherecal['status']        = ['EQ','4'];   //未还款用户
      $wherecal['expire_time']   = ['LT',time()];
      $count = $model->where($wherecal)->count();
      if(IS_POST){
        $overday = I('post.overdue');
        //$where['mauto']            = '2';         //系统筛选
        $where['collection_id']    = '0';         //未被领取
        $where['status']           = '4';         //待还订单
       // $where['login_id']         = '0';         //未被领单
        if($count>295)      $this->mtReturn(200,'已达上限！'.$count.'条',$_REQUEST['navTabId'],true,'','collection');

        $Orders = $model->where($where)->field('order_id,expire_time')->select();
        $overdueTime = $this->overdueTime($Orders);
        if($overday == 0){
            $val = array_slice($overdueTime['val'],0,10);
        }elseif($overday == 1){
            $val = array_slice($overdueTime['val1'],0,10);
        }elseif ($overday == 2) {
            $val = array_slice($overdueTime['val2'],0,10);
        }else{
            $val = array_slice($overdueTime['val3'],0,10);
        }
        if(empty($val)) $this->mtReturn(200,'暂无待处理订单'.$id,$_REQUEST['navTabId'],true,'','collection');
        $str = implode(array_column($val,'order_id'),',');
        $wheresave['order_id'] = ['IN',implode(array_column($val, 'order_id'),',')];
        $save   = $model->where($wheresave)->save(['collection_id'=>$uid,'collection_gtime'=>time()]);

        if($save)          $this->mtReturn(200,'成功领取'.$str,$_REQUEST['navTabId'],true,'','collection');
      }
      $this->assign('count',$count);
      $this->display();

  }

  //催收领取时间操作
  public function overdueTime($order){
    for($i=0;$i<count($order);$i++){
        $overday = overdue($order[$i]['expire_time']);
        if($overday == 0){
            $val['val'][] = $order[$i];
        }elseif($overday<0 && $overday >= -5){
            $val['val1'][] = $order[$i];
        }elseif($overday<-5 && $overday>=-10){
            $val['val2'][] = $order[$i];
        }elseif($overday < -10){
            $val['val3'][] = $order[$i];
        }
    }
    return $val;
  }

  //退还订单操作
  public function send_back(){
    $model = D($this->dbname);
    $order_id = $_GET['order_id'];
    $model->collection_id = 0;
    $result = $model->where("order_id = {$order_id}")->save();
    if($result){
        $this->mtReturn(200,'退还成功'.$order_id,$_REQUEST['navTabId'],false,'collection');
    }else{
        $this->mtReturn(200,'退还失败'.$order_id,$_REQUEST['navTabId'],false,'collection');
    }
  }

  //催收群发短信
  // public function duanxin(){
    
  //   if(IS_POST){
  //        $name = $_REQUEST['name'];
  //        $phone = $_REQUEST['phone'];
  //        $msg = $name.'在微耳钱包的账单已经逾期，通知今日还款。感谢您的理解与配合--';
  //        $code = new CodeController();
  //        $val = $code->msgSend($phone,$msg);
  //        if($val == 0){
  //           $this->mtReturn(200,"短信发送成功",$_REQUEST['navTabId'],true,'','collection'); 
  //        }else{
  //           $this->mtReturn(400,"短信发送失败",$_REQUEST['navTabId'],true,'','collection');
  //        }
  //   }else{
  //       $uid = D($this->dbname)->field('uid')->where("order_id = {$_REQUEST['order_id']}")->find();
  //       $name = $_REQUEST['name'];
  //       $apis = $this->api($uid['uid']);
  //       $file = json_decode($apis,true);
  //       $result = json_decode($file['data'],true)['contactAnalysis'];
  //       foreach($result as $k=>$v){
  //           if(preg_match("/^1[34578]{1}\d{9}$/",$v['callNum'])){
  //               $phone .= $v['callNum'].','; 
  //           }

  //       }
  //       $this->assign('name',$name);
  //       $this->assign('phone',$phone);
  //       $this->display();
  //   }
  // }

  //批量发送短信
  public function duanxin(){
    if(count($_REQUEST['val'])>5){
        var_dump('短信发送数量不得多于5条');exit;
    }
    $str = implode(',',$_REQUEST['val']);
    $msg = $_REQUEST['name'].'在微耳钱包的账单已经逾期，通知今日还款。感谢您的理解与配合--';
    $code = new CodeController();
    $val = $code->msgSend($str,$msg);
    if($val == 0){
        $uid = D($this->dbname)->where("order_id = {$_REQUEST['order_id']}")->field('uid')->find();
        $valP = M('cash_duanxin')->where("uid = {$uid['uid']}")->field('phone')->find();
        if($valP == null){
            $array['uid'] = $uid['uid'];
            $array['phone'] = '0,'.$str;
            $array['create_time'] = time();
            $result = M('cash_duanxin')->add($array);
        }else{
            $str2 = $valP['phone'].','.$str;
            $array['phone'] = $str2;
            $result = M('cash_duanxin')->where("uid = {$uid['uid']}")->save(['phone'=>$str2]);
        }
        if($result){
            $this->mtReturn(200,"短信发送成功",$_REQUEST['navTabId'],true,'','collection');
        }
   }else{
        $this->mtReturn(400,"短信发送失败",$_REQUEST['navTabId'],true,'','collection');
    }
    
  }

  //单条短信发送
  public function codes(){
    //var_dump($_REQUEST);exit;
    $uid = D($this->dbname)->field('uid')->where("order_id = {$_REQUEST['order_id']}")->find();
    $yuqi = overdue($_REQUEST['day']);
    if($yuqi >= 0){
       $msg = '您在微耳钱包的欠款今天到期,明天会产生滞纳金,最重要的是会对您的下次借款和额度提升产生不利影响,为避免给您生活带来不便,请于今日完成还款';
    }else{
       $msg = '您的账单已经逾期,为避免给您生活带来不便,请尽快完成还款';
    }
    $model = new CodeController();
    $val = $model->msgSend($_REQUEST['phone'],$msg);
    if($val == 0){
            $this->mtReturn(200,"短信发送成功",$_REQUEST['navTabId'],false,'','collection'); 
        }else{
            $this->mtReturn(400,"短信发送失败",$_REQUEST['navTabId'],false,'','collection');
    }
  }
  //催收管理
  public function collection(){

    $field = 'cash_order.*,mob.mobile_phone,info.user_name,gold.number';
    $model = D($this->dbname)->join('cash_user_info as info ON cash_order.uid = info.id', 'LEFT')
                             ->join('cash_user_mobile as mob ON cash_order.uid = mob.uid','LEFT')
                             ->join('cash_user_gold as gold ON cash_order.uid = gold.uid','LEFT');
    $map   = array();
    if(in_array($_REQUEST['collection_time'],['2','3'])){
        $field .= ',dk.over_day,dk.k_time,dk.k_time,dk.trans_type';
        $model = $model->join('cash_bf_dk as dk ON cash_order.order_id = dk.order_id');
    }
    $page = '';
     if (method_exists($this, '_collfilter')) {
            $val = $this->_collfilter($map,$page);
     }
	 $map = $val['map'];
	 $page = $val['page'];
     $this->_list($model,$map,False,$field,false,false,$page);
     $this->display();
  }
 
  public function inform(){
        if(IS_POST){
            $model = D($this->dbname);
            $arr['collection_time'] = $_POST['credit'];
            $result = $model->where("order_id = {$_REQUEST['order_id']}")->save($arr);
            if($result){
                $this->mtReturn(200,"添加成功",$_REQUEST['navTabId'],true,'','collection');
            }else{
                $this->mtReturn(200,"修改失败",$_REQUEST['navTabId'],true,'','collection'); 
            }
            
        }else{
            $order_id = $_REQUEST['order_id'];
            $this->assign('order_id',$order_id);
            $this->display();
        }
       
        // $model = D($this->dbname);
        // $id    = $_REQUEST [$model->getPk()];
        // $map   = ['order_id'=>$id,'collection_id'=>session('uid')];
        // $data  = $model->find($id);
        // $data['collection_time'] = time();
        // $save  = $model->save($data);
        // if($save){
        //     $msg = '标记成功';
        // }else{
        //     $msg = '标记失败';
        // }
        // $this->mtReturn(200,$msg.$id,$_REQUEST['navTabId'],false);
  }



  //进度记录
  public function spendwrite(){
    
    $model           = D($this->dbname);
    $spw             = M('cash_order_spendwrite');
    $id              = $_REQUEST[$model->getPk()];
    $login_id        = session('uid');
    $credit          = isset($_POST['credit'])?$_POST['credit']:0;
    if(IS_POST){
        //var_dump($_REQUEST);exit;
        $arr['login_id']          = $login_id;
        $arr['order_id']          = $id;
        $arr['message']           = $_POST['collection_mes'];
        $arr['creat_time']        = time();
        $arr['spend_type']        = $credit;
        $order['collection_time'] = $credit;
        $result = $spw->add($arr);
        $results = $model->where("order_id = {$id}")->save($order);
        $this->mtReturn(200,"添加成功".$id,$_REQUEST['navTabId'],true,'','collection');     

    }else{
        $result  = $spw->join("xy_user ON cash_order_spendwrite.login_id = xy_user.id","RIGHT")->where("order_id = {$id}")->field('xy_user.username,cash_order_spendwrite.message,cash_order_spendwrite.creat_time,cash_order_spendwrite.order_id,cash_order_spendwrite.spend_type')->select();
        foreach($result as $key => $val){   
            $result[$key]['spend_type'] = $this->mesg($val['spend_type']);
        }
        $this->assign('list',$result);
        $this->assign('id',$id);
        $this->display();
    }
  }

  //collection_time转换操作
  private function mesg($message){
    switch ($message) {
        case '1': $message = '承诺还款';break;
        case '2': $message = '敷衍跳票';break;
        case '3': $message = '拒绝还款';break;
        case '4': $message = '无人接听';break;
        case '5': $message = '正在通话';break;
        case '6': $message = '呼叫转移';break;
        case '7': $message = '关机';break;
        case '8': $message = '停机';break;
        case '9': $message = '空号';break;
        default : $message = '未知';break;     
    }
    return $message;
  }

  //续期记录
  public function continueList(){
        $model = D('cash_bf_dk as dk');
        $id    = $_REQUEST ['order_id'];
        $vo    = $model->join('xy_user as xy ON xy.id = dk.collection_id','LEFT')
                       ->where("dk.order_id = '{$id}' and dk.status = 'S'")
                       ->order('dk.k_time desc')
                       ->field('dk.*,xy.truename')
                       ->select();
        $this->assign('list', $vo);
        $this->display(); 
  }


  //加入黑名单操作
  public function blacklist(){
    if(IS_POST){
      $model = M('cash_user_info');
      $uid = $_POST['uid'];
      $order['order_id'] = $_REQUEST['order_id'];
      $black = M('cash_blacklist');
      $blackSearch = $this->blackSearch($uid);
      if($blackSearch){
          $arr['desc'] = $_POST['desc'];
          $arr['times'] = time();
          $arr['create_uid'] = session('uid');
          $result = $black->data($arr)->where("uid = {$uid}")->save();
      }else{
          $val = $model
                      ->join('cash_user_bank ON cash_user_info.id = cash_user_bank.uid')->field('cash_user_info.user_name,cash_user_bank.yu_tel,cash_user_info.user_idcard')->where("cash_user_info.id = {$uid}")->find();
          $arr['uid'] = $uid;
          $arr['user_name'] = $val['user_name'];
          $arr['mobile'] = $val['yu_tel'];
          $arr['user_idcard'] = $val['user_idcard'];
          $arr['desc'] = $_POST['desc'];
          $arr['times'] = time();
          $arr['create_uid'] = session('uid');
          $result = $black->add($arr);
      }
      $modelorder = D($this->dbname);
      $sta['status'] = -2;
      $suffit = '/re/'.$_POST['suffit'];
      if($result){
          $result = D($this->dbname)->where($order)->save($sta);
          $this->mtReturn(200,"修改成功".$uid,$_REQUEST['navTabId'],true,$suffit); 
      }else{
          $this->mtReturn(202,"修改失败".$uid,$_REQUEST['navTabId'],true,$suffit);
      }
    }else{
      $this->assign('order_id',$_GET['id']);
      $this->assign('suffit',$_GET['suffit']);
      $this->assign('uid',$_GET['uid']);
      $this->display();
    }
  }

  //添加黑名单前的查询操作
  public function blackSearch($uid){
    $model = M('cash_blacklist');
    $result = $model->where("uid = {$uid}")->find();
    if($result){
        return true;
    }else{
        return false;
    }
  }

  //拒绝短信
  public function code($uid,$number,$cat,$re){
      $result = M('cash_user_credit');
      $user = M('cash_user_info');
      $userN = $user->field('user_name')->where("id = {$uid}")->find();
      $phone = M('cash_user_mobile')->field('mobile_phone')->where("uid = {$uid}")->find();
      $val = $result->field('user_info,identity,bankcard,mobile_phone')->where("uid = {$uid}")->find();
      $ps = in_array($number,$val);
      if(!$ps){
        $arr['name'] = "{$userN['user_name']}";
        $result = $this->sendShortsms('SMS_89070008',$phone['mobile_phone'],$arr,C('AlidayuTitle'));
        if(!$result){
          $this->mtReturn(202,"提交失败",$cat['navTabId'],true,$re);
        }
      }
  }


  //搜索操作
  public function seek(){
    var_dump($_REQUEST);exit;
    if(is_array($_POST['keys'])){
        $uid = $_POST['keys'][0];
        $suffit = $_POST['suffit'][0];
    }else{
        $uid = $_POST['keys'];
        $suffit = $_POST['suffit'];
    }
    if(!is_numeric($uid)){
      $uid = $this->uname($uid)['id'];
    }
    $model = D($this->dbname);
    $result = $model
                  ->join('cash_user_credit ON cash_order.uid = cash_user_credit.uid');
    $re = $this->seek_condition($uid);
    $this->_list($result,$re);
    $this->assign('suffit',$suffit);
    $this->display('index');
  }

  //搜索条件
  public function seek_condition($uid){
    $map = array();
    $map['cash_order.uid'] = $uid;
    $map['cash_order.status'] = 1;
    $map['cash_order.login_id'] = session('uid');
    return $map;
  }

  //根据用户名获取uid
  public function uname($uid){
    $arr['user_name'] = $uid;
    $uid = M('cash_user_info')->field('id')->where($arr)->find();
    return $uid;
  }

  //结算
  public function settlement(){

    $model = D($this->dbname);
    $field = 'cash_order.*,info.user_name,mob.mobile_phone'; 
    $model = $model->join('cash_user_info as info ON info.id = cash_order.uid','LEFT')
                   ->join('cash_user_mobile as mob ON cash_order.uid = mob.uid','LEFT');
    $map = array();
    $this->_filtersettlement($map);
    $this->_list($model,$map,False,$field);
    $this->display();
  }
  
  private function _filtersettlement(&$map){
    $map['cash_order.status'] = $_REQUEST ['cash_order']?$_REQUEST['cash_order']:'4'; //待还订单 
    $_REQUEST ['orderField']  = $_REQUEST ['orderField']?$_REQUEST ['orderField']:'expire_time';
    if(isset($_REQUEST['keys']) && $_REQUEST['keys'] != ''){
        $map['info.user_name|cash_order.order_id']   = ['like','%'.urldecode(trim($_REQUEST['keys'])).'%'];     
    }
    if(isset($_REQUEST['id']) && $_REQUEST['id'] != ''){
        $map['cash_order.order_id'] = $_REQUEST['id'];
    }

  }

   //订单处理
  public function handle(){
   
    $model = D($this->dbname);
 
    if(IS_POST){

        if(!in_array(session('uid'),C('ADMINISTRATOR'))) $this->mtReturn(200,'您没有该权限,请勿非法操作!',$_REQUEST['navTabId'],true,'','settlement');
        
        $dotype  = I('POST.dotype');
        $order_id= I('POST.order_id')?I('POST.order_id'):$this->mtReturn(200,'参数丢失~~！！',$_REQUEST['navTabId'],true,'','settlement');
        $do_time = I('POST.k_time')?I('POST.k_time'):date('Y-m-d H:i:s');
        $uid     = I('POST.uid'); 

        $where   = ['order_id'=>$order_id,'uid'=>$uid,'status'=>'4' ];
        $check_type = $model->where($where)->find();
        if(empty($check_type)) $this->mtReturn(200,'无效的订单··！'.$order_id,$_REQUEST['navTabId'],true,'','settlement');

        $add['k_time']       = strtotime($do_time);
        $add['order_id']     = $order_id;
        $add['uid']          = $uid;
        $add['status']       = 'S';
        $collection_id       = $model->where("order_id = '{$order_id}'")->getField('collection_id');

        if( $dotype == 1 ){           //确认还款
            $save['status']       = 5;
            $add ['succ_amt']     = I('POST.repayment_amount')*100;
            $add ['trans_type']   = 2;
            $add ['collection_id']= $collection_id;

            $msg = '确认收款成功 单号：'.$order_id.' 负责人'.$collection_id;
            if( I('post.all') == 1 ){ //全款
                $add['succ_amt']  = I('POST.shouldmoney')*100;
            }else{                    //折扣
                $add['succ_amt']  = I('POST.discount') == '' ? I('POST.shouldmoney')*100 : I('POST.discount')*100;
                $add['discount']  = I('POST.discount') == '' ? 0 :I('POST.shouldmoney') - I('POST.discount');
                $msg.=' 折扣：'.$add['discount'].'元';
            }

        }else{                       //续期

            $time = $check_type['expire_time'] > time() ? $check_type['expire_time'] : time();
            $save['expire_time']  = $time + 86400*I('POST.days');

            if( $check_type['interest'] == '0.01' ){
                $income = M('cash_goods')->where("money = '{$check_type['money']}' and days = '{$_POST['days']}'")->getField('income');
            }else{
                $income = $check_type['money'] * $check_type['interest'];
            }

            $save['repayment_amount'] = $check_type['money'] + $income;
            $save['income']           = $income;

            $money                = I('POST.truemoney') == '' ? I('POST.money') : I('POST.truemoney');
            $add['succ_amt']      = $money * 100;
            $add['trans_type']    = 3;
            $add['over_day']      = I('POST.days');
            $add['collection_id'] = $collection_id;

            $msg = $order_id.'成功延期:'.I('POST.days').'天 费用：'.$money.'元 到期时间：'.date('Y-m-d H:i:s', $save['expire_time']).' 到期金额：'.$save['repayment_amount'].'负责人'.$collection_id;
        }
        M()->startTrans();
        $save = $model->where($where)->data($save)->save();
        $add  = M('cash_bf_dk')->add($add);
        if($save && $add){
            M()->commit();
            $this->mtReturn(200,$msg,$_REQUEST['navTabId'],true,'','settlement');
        }else{
            M()->rollback();
            $this->mtReturn(200,'操作失败！！'.$order_id,$_REQUEST['navTabId'],true,'','settlement');
        }
    }
    $field = 'cash_order.*,info.user_name,mob.mobile_phone'; 
    $model = $model->join('cash_user_info as info ON info.id = cash_order.uid','LEFT')
                   ->join('cash_user_mobile as mob ON cash_order.uid = mob.uid','LEFT');
    $this->_filtersettlement($map);
    $list = $model->where($map)->field($field)->find();
    $this->assign('id',$_REQUEST['id']);
    $this->assign('list',$list);
    $this->display();
  }




  //用户订单详情操作
  public function userorder(){
    
    $field = "id,user_name";
    //获取借款成功的所有用户的id
    $uid = M('cash_user_info')->join('cash_order ON cash_order.uid = cash_user_info.id');
    //$map = array();
	$page = '';
    $val = $this->_userordersearch($map,$page);
	$map = $val['map'];
    $page = $val['page'];
    $this->_list($uid,$map,false,$field,2,true,$page);
    $this->display();
  }

  //用户订单详情查询删选条件
  public function _userordersearch($map,$page){
       $map['cash_order.status'] = 5;
       if(isset($_REQUEST['keys']) && $_REQUEST['keys'] != ''){
            $map['cash_user_info.user_name|cash_order.order_id']   = ['like','%'.urldecode(trim($_REQUEST['keys'])).'%'];     
       }
	   if(isset($_REQUEST['page']) && !empty($_REQUEST['page'])){
		   $page = $_REQUEST['page'];
	   }
        $arr['map'] = $map;
	    $arr['page'] = $page;
        return $arr;		
  }

  //用户借款订单详情
  public function details(){
    $uid = I('get.id');
    $result = M('cash_user_info')->join('cash_order ON cash_order.uid = cash_user_info.id')->where("cash_order.status = 5 AND cash_order.uid = {$uid}")->field('cash_order.loan_time,cash_order.order_id')->select();
    for($i=0;$i<count($result);$i++){
       $result[$i][] = M('cash_bf_dk')->field('k_time,trans_type,trans_type')->where("order_id = {$result[$i]['order_id']} AND trans_type != 3 AND status = 'S'")->select();
       $result[$i][] = M('cash_bf_dk')->where("order_id = {$result[$i]['order_id']} AND trans_type = 3")->count();
    }
  // var_dump($result[0]);exit;
    $this->assign('msg',$result);
    $this->display();
  }


  //联系人备注操作
  public function linkman(){
    if(IS_POST){
        $model = M('cash_linkman');
        $login_id = session('uid');
        $val = $model->where("phone = {$_REQUEST['phone']}")->find();
        $arr['message'] = $_REQUEST['reason'];
        if($val){
            $result = $model->where("phone = {$_REQUEST['phone']} AND order_id = {$_REQUEST['order_id']}")->save($arr);
        }else{
            $arr['order_id'] = $_REQUEST['order_id'];
            $arr['phone'] = $_REQUEST['phone'];
            $arr['login_id'] = $login_id;
            $arr['creat_time'] = time();
            $result = $model->add($arr);
        }
        
        if($result){
            $this->mtReturn(200,"添加成功",$_REQUEST['navTabId'],true);
        }else{
            $this->mtReturn(200,"添加失败",$_REQUEST['navTabId'],true);
        }
    }else{
        $this->assign('phone',$_REQUEST['phone']);
        $this->assign('order_id',$_REQUEST['order_id']);
        $this->display();
    }
  }

  /**
   * [transactionType 查讯当天交易状态]
   * @return [type]
   */
  public function transactionType(){

        $order_id = $_REQUEST['order_id'];
        $where['k_time']  = [ 'BETWEEN',[strtotime(date('Y-m-d 0:0:0',time())),strtotime(date('Y-m-d 23:59:59',time()))] ];
        $where['order_id']= $order_id;
        $where['status']  = 'S';
        $type = M('cash_bf_dk')->where($where)->getField('trans_type');
        $this->ajaxReturn($type,'json');

  }
}
